package com.huang.controller;

import com.aliyun.oss.OSSClient;
import com.huang.config.AliyunConfig;
import com.huang.entity.Img;
import com.huang.service.ImgService;
import com.huang.util.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;


@RestController
@RequestMapping("oss")
public class ImgController {

    // 允许上传的格式
    private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg", ".jpeg", ".gif", ".png"};

    @Autowired
    private OSSClient ossClient;

    @Autowired
    private AliyunConfig aliyunConfig;

    @Autowired
    private ImgService imgService;

    @PostMapping
    public Result upload(@RequestParam("file") MultipartFile file, @RequestParam("userId") Long userId,
                         @RequestParam("introduction") String intro, @RequestParam("content") String content) {
        // 1. 对上传的图片进行校验: 这里简单校验后缀名
        // 另外可通过ImageIO读取图片的长宽来判断是否是图片,校验图片的大小等。
        // 图片校验
        boolean isLegal = false;
        for (String type : IMAGE_TYPE) {
            if (StringUtils.endsWithIgnoreCase(file.getOriginalFilename(), type)) {
                isLegal = true;
                break;  // 只要与允许上传格式其中一个匹配就可以
            }
        }
        // 格式错误, 返回与前端约定的error
        if (!isLegal) {
            return Result.fail(200, "图片格式错误");
        }

        // 2. 准备上传API的参数
        String originalFilename = file.getOriginalFilename();
        String filename = UUID.randomUUID().toString() + "." + StringUtils.substringAfter(originalFilename, ".");
        try {
            ossClient.putObject(aliyunConfig.getBucketName(), filename, new ByteArrayInputStream(file.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
            // 上传失败
            return Result.fail(200, "图片上传失败");
        }
        String imgUrl = aliyunConfig.getUrlPrefix() + filename;
        // 将图片url插入到数据库
        Date date = new Date();
        Img img = new Img();
        img.setUserId(userId);
        img.setUserImg(imgUrl);
        img.setContent(content);
        img.setIntroduction(intro);
        img.setCreateDate(date.getTime());
        //保存到数据库
        imgService.save(img);
        return Result.success("日记添加成功", null);
    }
}
